<template>
    <div class="admin-management">
        <!-- 搜索和操作区域 -->
        <div class="search-operation">
            <el-card shadow="never">
                <div class="search-form">
                    <el-form :model="searchForm" inline>
                        <el-form-item label="管理员ID">
                            <el-input v-model="searchForm.admin_id" placeholder="请输入管理员ID" clearable
                                style="width: 120px" />
                        </el-form-item>
                        <el-form-item label="管理员名称">
                            <el-input v-model="searchForm.admin_name" placeholder="请输入管理员名称" clearable
                                style="width: 150px" />
                        </el-form-item>
                        <el-form-item label="邮箱">
                            <el-input v-model="searchForm.email" placeholder="请输入邮箱" clearable style="width: 200px" />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
                            <el-button @click="handleReset" :icon="Refresh">重置</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </el-card>
        </div>

        <!-- 管理员列表 -->
        <div class="admin-list">
            <el-card shadow="never">
                <template #header>
                    <div class="table-header">
                        <span>管理员列表</span>
                        <div>
                            <el-button type="primary" @click="handleCreate" :icon="Plus">新增管理员</el-button>
                        </div>
                    </div>
                </template>

                <el-table :data="adminList" v-loading="loading" border stripe style="width: 100%">
                    <el-table-column prop="admin_id" label="管理员ID" width="100" align="center" />
                    <el-table-column prop="admin_name" label="管理员名称" min-width="120" />
                    <el-table-column prop="email" label="邮箱" min-width="200" />
                    <el-table-column prop="last_login" label="最后登录" width="180">
                        <template #default="{ row }">
                            {{ formatDate(row.last_login) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="created_at" label="创建时间" width="180">
                        <template #default="{ row }">
                            {{ formatDate(row.created_at) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200" fixed="right" align="center">
                        <template #default="{ row }">
                            <el-button size="small" type="primary" link @click="handleEdit(row)" :icon="Edit">
                                编辑
                            </el-button>
                            <el-button size="small" type="danger" link @click="handleDelete(row.admin_id)"
                                :icon="Delete">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <div class="pagination">
                    <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.pageSize"
                        :page-sizes="[10, 20, 50, 100]" :total="pagination.total"
                        layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" />
                </div>
            </el-card>
        </div>

        <!-- 新增/编辑管理员对话框 -->
        <el-dialog v-model="formDialogVisible" :title="formTitle" width="500px" destroy-on-close>
            <el-form ref="adminFormRef" :model="adminForm" :rules="adminFormRules" label-width="100px">
                <el-form-item label="管理员名称" prop="admin_name">
                    <el-input v-model="adminForm.admin_name" placeholder="请输入管理员名称" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="adminForm.email" placeholder="请输入邮箱" />
                </el-form-item>
                <el-form-item label="密码" prop="password" v-if="isCreate">
                    <el-input v-model="adminForm.password" type="password" placeholder="请输入密码" show-password />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="formDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="formLoading">
                    确定
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
    Search,
    Refresh,
    Plus,
    Edit,
    Delete
} from '@element-plus/icons-vue'
import {
    getAdmins,
    createAdmin,
    updateAdmin,
    getAdminDetail,
    deleteAdmin
} from '@/api/admin'
import { validateEmail } from '@/utils/validate'

const loading = ref(false)
const formDialogVisible = ref(false)
const formLoading = ref(false)
const adminFormRef = ref()
const currentAdmin = ref(null)
const adminList = ref([])

// 搜索表单
const searchForm = reactive({
    admin_id: '',
    admin_name: '',
    email: ''
})

// 分页配置
const pagination = reactive({
    page: 1,
    pageSize: 10,
    total: 0
})

// 管理员表单
const adminForm = reactive({
    admin_name: '',
    email: '',
    password: ''
})

// 修改密码表单
const changePasswordForm = reactive({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
})

// 表单验证规则
const adminFormRules = {
    admin_name: [
        { required: true, message: '请输入管理员名称', trigger: 'blur' },
        { min: 2, max: 20, message: '管理员名称长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (!value) {
                    callback(new Error('请输入邮箱'))
                } else if (!validateEmail(value)) {
                    callback(new Error('请输入正确的邮箱格式'))
                } else {
                    callback()
                }
            }, trigger: 'blur'
        }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
    ]
}

// 计算属性
const formTitle = computed(() => {
    return isCreate.value ? '新增管理员' : '编辑管理员'
})

const isCreate = computed(() => {
    return !currentAdmin.value?.admin_id
})

// 工具函数
const formatDate = (dateString) => {
    if (!dateString) return '-'
    try {
        const date = new Date(dateString)
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        }).replace(/\//g, '-')
    } catch (error) {
        return dateString
    }
}

// 页面加载时获取管理员列表
onMounted(() => {
    fetchAdmins()
})

// 获取管理员列表
const fetchAdmins = async () => {
    try {
        loading.value = true

        const params = {
            page: pagination.page,
            pageSize: pagination.pageSize,
            ...searchForm
        }

        // 清理空值参数
        Object.keys(params).forEach(key => {
            if (params[key] === '' || params[key] === null || params[key] === undefined) {
                delete params[key]
            }
        })

        const response = await getAdmins(params)

        if (response.code === 0) {
            adminList.value = response.data.list || response.data
            pagination.total = response.data.total || response.data.length || 0
        } else {
            ElMessage.error(response.msg || '获取管理员列表失败')
        }
    } catch (error) {
        ElMessage.error('网络错误，请稍后重试')
        console.error('获取管理员列表失败:', error)
    } finally {
        loading.value = false
    }
}

// 搜索管理员
const handleSearch = () => {
    pagination.page = 1
    fetchAdmins()
}

// 重置搜索
const handleReset = () => {
    Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
    })
    pagination.page = 1
    fetchAdmins()
}

// 分页大小改变
const handleSizeChange = (newSize) => {
    pagination.pageSize = newSize
    pagination.page = 1
    fetchAdmins()
}

// 当前页改变
const handleCurrentChange = (newPage) => {
    pagination.page = newPage
    fetchAdmins()
}

// 新增管理员
const handleCreate = () => {
    currentAdmin.value = null
    resetForm()
    formDialogVisible.value = true
}

// 编辑管理员
const handleEdit = async (admin) => {
    try {
        // 确保 admin_id 是数字类型
        const adminId = parseInt(admin.admin_id)
        const response = await getAdminDetail(adminId)

        if (response.code === 0) {
            currentAdmin.value = response.data
            Object.keys(adminForm).forEach(key => {
                if (currentAdmin.value[key] !== undefined) {
                    adminForm[key] = currentAdmin.value[key]
                }
            })
            // 编辑时不需要密码字段
            adminForm.password = ''
            formDialogVisible.value = true
        } else {
            ElMessage.error(response.msg || '获取管理员信息失败')
        }
    } catch (error) {
        ElMessage.error('获取管理员信息失败')
        console.error('获取管理员信息失败:', error)
    }
}

// 删除管理员
const handleDelete = async (adminId) => {
    try {
        await ElMessageBox.confirm(
            '确定要删除该管理员吗？此操作不可恢复！',
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )

        // 确保 admin_id 是数字类型
        const id = parseInt(adminId)
        const response = await deleteAdmin(id)

        if (response.code === 0) {
            ElMessage.success('删除管理员成功')
            fetchAdmins()
        } else {
            ElMessage.error(response.msg || '删除管理员失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除管理员失败')
            console.error('删除管理员失败:', error)
        }
    }
}

// 提交表单（新增/编辑）
const handleSubmit = async () => {
    if (!adminFormRef.value) return

    try {
        await adminFormRef.value.validate()
        formLoading.value = true

        let response

        if (isCreate.value) {
            // 新增管理员
            response = await createAdmin(adminForm)

            if (response.code === 0) {
                ElMessage.success('创建管理员成功')
                formDialogVisible.value = false
                fetchAdmins()
            } else {
                ElMessage.error(response.msg || '创建管理员失败')
            }
        } else {
            // 编辑管理员 - 只更新管理员名称和邮箱，不更新密码
            const submitData = {
                admin_name: adminForm.admin_name,
                email: adminForm.email
            }

            // 确保 admin_id 是数字类型
            const adminId = parseInt(currentAdmin.value.admin_id)

            response = await updateAdmin(adminId, submitData)

            if (response.code === 0) {
                ElMessage.success('更新管理员成功')
                formDialogVisible.value = false
                fetchAdmins()
            } else {
                ElMessage.error(response.msg || '更新管理员失败')
            }
        }
    } catch (error) {
        if (error.errors) {
            ElMessage.error('请完善表单信息')
        } else {
            ElMessage.error(isCreate.value ? '创建管理员失败' : '更新管理员失败')
            console.error('表单提交失败:', error)
        }
    } finally {
        formLoading.value = false
    }
}

// 重置表单
const resetForm = () => {
    Object.keys(adminForm).forEach(key => {
        adminForm[key] = ''
    })

    if (adminFormRef.value) {
        adminFormRef.value.clearValidate()
    }
}
</script>

<style scoped>
.admin-management {
    padding: 20px;
}

.search-operation {
    margin-bottom: 20px;
}

.search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.admin-list {
    margin-bottom: 20px;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
</style>